package com.doujiang.Controller;

import com.doujiang.domain.Rating;
import com.doujiang.service.ICommentService;
import com.doujiang.service.IMovieService;
import com.doujiang.service.IRatingService;
import com.doujiang.domain.Comment;
import com.doujiang.domain.Movie;
import com.doujiang.service.zzqICommentService;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import org.springframework.http.ResponseEntity;

@RestController
@RequestMapping("/movie")
public class zzqMovieController {

    private final IMovieService movieService;
    private final zzqICommentService commentService;
    private final IRatingService ratingService;

    public zzqMovieController(IMovieService movieService, zzqICommentService commentService, IRatingService ratingService) {
        this.movieService = movieService;
        this.commentService = commentService;
        this.ratingService = ratingService;
    }

    /**
     * 测试接口 - 验证评分数据格式
     */
    @GetMapping("/test-rating-data/{movieId}")
    public ResponseEntity<String> testRatingData(@PathVariable("movieId") Long movieId) {
        try {
            List<Rating> ratings = ratingService.getRatingsByMovieId(movieId);
            StringBuilder result = new StringBuilder();
            result.append("电影").append(movieId).append("的评分数据：\n");
            
            for (Rating rating : ratings) {
                result.append("用户ID: ").append(rating.getUserId())
                      .append(" (类型: ").append(rating.getUserId().getClass().getSimpleName()).append(")")
                      .append(", 评分: ").append(rating.getScore())
                      .append(" (类型: ").append(rating.getScore().getClass().getSimpleName()).append(")")
                      .append("\n");
            }
            
            return ResponseEntity.ok(result.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("获取评分数据失败: " + e.getMessage());
        }
    }

    /**
     * 测试接口 - 验证评分功能
     */
    @GetMapping("/test-rating")
    public ResponseEntity<String> testRating() {
        try {
            // 测试查询评分
            List<Rating> ratings = ratingService.getRatingsByMovieId(100L);
            return ResponseEntity.ok("评分功能正常，电影100的评分数量: " + ratings.size());
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("评分功能异常: " + e.getMessage());
        }
    }

    /**
     * 测试接口 - 电影推荐数据格式示例
     */
    @GetMapping("/test-movie-recommendations")
    public ResponseEntity<String> testMovieRecommendations() {
        try {
            // 模拟AI推荐的电影数据格式
            String aiResponse = "根据你的观影偏好，我为你推荐以下电影：\n\n" +
                    "{{MOVIE_RECOMMENDATIONS}}" +
                    "[" +
                    "{\"id\":1,\"title\":\"肖申克的救赎\",\"year\":1994,\"genre\":\"剧情\",\"director\":\"弗兰克·德拉邦特\",\"score\":9.7,\"poster\":\"https://img2.doubanio.com/view/photo/s_ratio_poster/public/p480747492.jpg\"}," +
                    "{\"id\":2,\"title\":\"霸王别姬\",\"year\":1993,\"genre\":\"剧情\",\"director\":\"陈凯歌\",\"score\":9.6,\"poster\":\"https://img1.doubanio.com/view/photo/s_ratio_poster/public/p1910813120.jpg\"}," +
                    "{\"id\":3,\"title\":\"阿甘正传\",\"year\":1994,\"genre\":\"剧情\",\"director\":\"罗伯特·泽米吉斯\",\"score\":9.5,\"poster\":\"https://img2.doubanio.com/view/photo/s_ratio_poster/public/p2372307693.jpg\"}," +
                    "{\"id\":4,\"title\":\"泰坦尼克号\",\"year\":1997,\"genre\":\"爱情\",\"director\":\"詹姆斯·卡梅隆\",\"score\":9.4,\"poster\":\"https://img3.doubanio.com/view/photo/s_ratio_poster/public/p457760035.jpg\"}," +
                    "{\"id\":5,\"title\":\"这个杀手不太冷\",\"year\":1994,\"genre\":\"动作\",\"director\":\"吕克·贝松\",\"score\":9.4,\"poster\":\"https://img2.doubanio.com/view/photo/s_ratio_poster/public/p511118051.jpg\"}" +
                    "]" +
                    "{{END_MOVIE_RECOMMENDATIONS}}\n\n" +
                    "这些电影都是经典之作，相信你会喜欢的！点击电影卡片可以查看详情。";
            
            return ResponseEntity.ok(aiResponse);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("获取电影推荐失败: " + e.getMessage());
        }
    }

    @GetMapping("/{id}")
    public Movie getMovieById(@PathVariable("id") Long id) {
        return movieService.getMovieById(id);
    }

    @GetMapping("/{id}/comments")
    public List<Comment> getCommentsByMovieId(@PathVariable("id") Long id) {
        return commentService.getCommentsByMovieId(id);
    }

    @PostMapping("/{id}/comment")
    public ResponseEntity<Boolean> saveComment(@PathVariable("id") Long id, @RequestBody Comment comment) {
        try {
            System.out.println("收到评论请求 - 电影ID: " + id);
            System.out.println("评论数据: " + comment);
            
            comment.setMovieId(id);
            // 确保必要字段不为空
            if (comment.getContent() == null || comment.getContent().trim().isEmpty()) {
                System.out.println("评论内容不能为空");
                return ResponseEntity.badRequest().body(false);
            }
            if (comment.getUserId() == null) {
                System.out.println("用户ID不能为空");
                return ResponseEntity.badRequest().body(false);
            }
            
            System.out.println("保存评论 - 用户ID: " + comment.getUserId() + ", 电影ID: " + comment.getMovieId() + ", 内容: " + comment.getContent());
            boolean result = commentService.saveComment(comment);
            System.out.println("评论保存结果: " + result);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            System.err.println("保存评论时发生错误: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(500).body(false);
        }
    }

    @GetMapping("/{id}/ratings")
    public ResponseEntity<List<Rating>> getRatingsByMovieId(@PathVariable("id") Long id) {
        try {
            List<Rating> ratings = ratingService.getRatingsByMovieId(id);
            return ResponseEntity.ok(ratings);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(null);
        }
    }

    @PostMapping("/{id}/rating")
    public ResponseEntity<Boolean> saveRating(@PathVariable("id") Long id, @RequestBody Rating rating) {
        try {
            System.out.println("收到评分请求 - 电影ID: " + id);
            System.out.println("评分数据: " + rating);
            
            rating.setMovieId(id);
            // 确保score是BigDecimal类型
            if (rating.getScore() == null) {
                System.out.println("评分不能为空");
                return ResponseEntity.badRequest().body(false);
            }
            
            System.out.println("保存评分 - 用户ID: " + rating.getUserId() + ", 电影ID: " + rating.getMovieId() + ", 评分: " + rating.getScore());
            boolean result = ratingService.saveRating(rating);
            System.out.println("评分保存结果: " + result);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            System.err.println("保存评分时发生错误: " + e.getMessage());
            e.printStackTrace();
            return ResponseEntity.status(500).body(false);
        }
    }
}
